package com.example.ymm.modules1.controller.hl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.entity.hl.dkn.*;
import com.example.ymm.modules1.query.hl.*;
import com.example.ymm.modules1.query.ms.VpmShengChanZuoYeJiHuaQueryCriteria;
import com.example.ymm.modules1.service.dkn.DknForecastService;
import com.example.ymm.modules1.service.dkn.DknOrderService;
import com.example.ymm.modules1.service.dto.dkn.DknEditOrderDto;
import com.example.ymm.modules1.service.dto.dkn.DknNotInOrderDto;
import com.example.ymm.modules1.service.dto.heng.DknProductMappingDto;
import com.example.ymm.modules1.service.dto.heng.ImportDknProductDto;
import com.example.ymm.modules1.service.dto.ms.MsOrderListQueryCriteria;
import com.example.ymm.modules1.service.dto.ms.VpmShengChanZuoYeJiHuaDto;
import com.example.ymm.modules1.service.hl.*;
import com.example.ymm.modules1.service.ms.VpmShengChanZuoYeJiHuaService;
import com.example.ymm.util.UtilValidate;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/hl/heng/dkn/product")
@Api(tags = "hl dkn 产品管理")
@Slf4j
public class DknProductController extends BaseController {

    @Autowired
    DknProductMappingService dknProductMappingService;

    @Autowired
    DknPurchaseOrderService dknPurchaseOrderService;

    @Autowired
    DknOrderService dknOrderService;

    @Autowired
    DknForecastService dknForecastService;

    @Autowired
    DknForecastProductService dknForecastProductService;

    @Autowired
    VpmShengChanZuoYeJiHuaService vpmShengChanZuoYeJiHuaService;

    @Autowired
    DknClosePlanService dknClosePlanService;

    @Autowired
    DknMainPlanService dknMainPlanService;
    @Autowired
    DknItemPlanService dknItemPlanService;
    @Autowired
    DknPlanItemService dknPlanItemService;

    @Autowired
    DknForecastCacheService dknForecastCacheService;
    @Autowired
    private DknForecastSaveService dknForecastSaveService;

    @ApiOperation(value = "产品列表")
    @PostMapping("/productList")
    public CommonResult productList(@Valid DknProductMappingQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<DknProductMapping> list = dknProductMappingService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "产品保存")
    @PostMapping("/productSave")
    public CommonResult productSave(DknProductMapping productMapping) {
        try {
            dknProductMappingService.saveOrUpdate(productMapping);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "产品删除")
    @PostMapping("/productRemove")
    public CommonResult productRemove(DknProductMapping productMapping) {
        try {
            dknProductMappingService.removeById(productMapping);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "产品导入")
    @PostMapping("/importDknProduct")
    public CommonResult importDknProduct(@RequestBody ImportDknProductDto dto) {
        try {
            List<String> strings = dknProductMappingService.importDknProduct(dto);
            return CommonResult.success(strings);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "订单列表")
    @PostMapping("/orderList")
    public CommonResult orderList(@Valid DknPurchaseOrderQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<DknPurchaseOrder> list = dknPurchaseOrderService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "订单物料信息")
    @PostMapping("/orderItemList")
    public CommonResult orderItemList(String inquiryCode) {
        try {
            JSONArray array = dknPurchaseOrderService.orderItemList(inquiryCode);
            return CommonResult.success(array, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询订单状态")
    @PostMapping("/orderStatus")
    public CommonResult orderStatus(String inquiryCode) {
        try {
            JsonNode jsonNode = dknOrderService.inquiriesOrder(inquiryCode);
            return CommonResult.success(jsonNode, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "订单取消")
    @PostMapping("/orderCancel")
    public CommonResult orderCancel(DknPurchaseOrder order) {
        try {
            dknPurchaseOrderService.orderCancel(order);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "订单详情")
    @PostMapping("/orderDetail")
    public CommonResult orderDetail(DknPurchaseOrder order) {
        try {
            JsonNode jsonNode = dknPurchaseOrderService.orderDetail(order);
            return CommonResult.success(jsonNode);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "查看已下订单之中哪些 没有映射到")
    @PostMapping("/itemNoMapping")
    public CommonResult itemNoMapping(String orderNo) {
        try {
            if(UtilValidate.isEmpty(orderNo)){
                return CommonResult.error("参数非法");
            }
            MsOrderListQueryCriteria criteria=new MsOrderListQueryCriteria();
            criteria.setOrderNo(orderNo);
            List<DknProductMappingDto> list = dknProductMappingService.purchaseOrderNoMappingList(criteria);
            return CommonResult.success(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "查看已下订单之中哪些 没有映射到")
    @PostMapping("/orderEditItem")
    public CommonResult orderEditItem(DknEditOrderDto editOrderDto) {
        try {
            JsonNode jsonNode = dknOrderService.postEditItem(editOrderDto);
            if(UtilValidate.isNotEmpty(jsonNode)){
                String errorDescription = jsonNode.get("error_description").textValue().trim();
                if(UtilValidate.isNotEmpty(errorDescription)){
                    return CommonResult.error("无法修改:"+errorDescription);
                }
            }
            return CommonResult.success(jsonNode);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "删除订单项")
    @PostMapping("/orderEditRemove")
    public CommonResult orderEditRemove(DknEditOrderDto editOrderDto) {
        try {
            JsonNode jsonNode = dknOrderService.postRemoveItem(editOrderDto);
            if(UtilValidate.isNotEmpty(jsonNode)){
                String errorDescription = jsonNode.get("error_description").textValue().trim();
                if(UtilValidate.isNotEmpty(errorDescription)){
                    return CommonResult.error("无法删除:"+errorDescription);

                }
            }
            return CommonResult.success(jsonNode);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "新增订单项")
    @PostMapping("/orderEditAdd")
    public CommonResult orderEditAdd(DknEditOrderDto editOrderDto) {
        try {
            JsonNode jsonNode = dknOrderService.postAddItem(editOrderDto);

            return CommonResult.success(jsonNode);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "物料计划列表")
    @RequestMapping(value = "/forecastList", method = RequestMethod.POST)
    public CommonResult forecastList(DklForecastQueryCriteria criteria,YmPageDto pageDto) {
        try{

//            JSONObject jsonObject = dknForecastService.forecastTableList(criteria, pageDto);
//
//
//            JSONObject data = jsonObject.getJSONObject("data");
//            JSONObject additionalPropeties=data.getJSONObject("additionalPropeties");
//            String snapshotWeek=additionalPropeties.getString("snapshotWeek");
//
//            String result = snapshotWeek.substring(0, 4) + "-W" + snapshotWeek.substring(4);
//            JSONArray jsonArray = data.getJSONArray("content");
//            JSONArray list = dknForecastService.forecastPlanSet(jsonArray, criteria,result);
//            data.put("content",list);
//            return CommonResult.success(data);
             JSONObject forecast = dknForecastCacheService.forecastDataList(criteria);
            return CommonResult.success(forecast.get("data"));

        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "查看已调整订单")
    @RequestMapping(value = "/yiTiaoZhengList", method = RequestMethod.POST)
    public CommonResult yiTiaoZhengList(@RequestBody JSONObject jsonObject) {
        try{
            List<JSONObject> jsonObjects = dknForecastService.yiTiaoZhengList(jsonObject);
            TableList<JSONObject> tableList = new TableList<>();
            tableList.setList(jsonObjects);
            tableList.setTotalResult(jsonObjects.size());
            return CommonResult.success(tableList);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "查看已调整订单")
    @RequestMapping(value = "/submitPlanData", method = RequestMethod.POST)
    public CommonResult submitPlanData(@RequestBody JSONArray array) {
        try{
            if(UtilValidate.isEmpty(array)){
                return CommonResult.error("数据不能为空!");
            }
            dknForecastService.submitPlanData(array);
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "forecast产品列表")
    @PostMapping("/forecastProductList")
    public CommonResult forecastProductList(@Valid DknForecastProductQueryCriteria criteria, YmPageDto ymPage) {
        try {

            TableList<DknForecastProduct> list = dknForecastProductService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "未入库的备货订单")
    @PostMapping("/notInOrderTable")
    public CommonResult notInOrderTable(@Valid DknForecastProductQueryCriteria criteria, YmPageDto ymPage) {
        try {

            TableList<DknNotInOrderDto> list = dknForecastProductService.notInOrderTable(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "forecast产品删除")
    @PostMapping("/forecastProductRemove")
    public CommonResult forecastProductRemove(DknForecastProduct productMapping) {
        try {
            dknForecastProductService.removeById(productMapping);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "forecast产品导入")
    @PostMapping("/importForecastProduct")
    public CommonResult importForecastProduct(@RequestBody List<DknForecastProduct> dtos) {
        try {
            List<String> strings = dknForecastProductService.importForecastProduct(dtos);
            return CommonResult.success(strings);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "dkn排产列表(订单分解)")
    @PostMapping("/queryDknTableList")
    public CommonResult queryDknTableList(@Valid VpmShengChanZuoYeJiHuaQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<VpmShengChanZuoYeJiHuaDto> list = vpmShengChanZuoYeJiHuaService.queryDknTableList(criteria,ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "排除计划项")
    @PostMapping("/addDknClosePlan")
    public CommonResult saveDknClosePlan(@RequestParam String biaoShiHao) {
        try {
             dknClosePlanService.saveDknClosePlan(biaoShiHao);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "还原计划项")
    @PostMapping("/removeDknClosePlan")
    public CommonResult removeDknClosePlan(@RequestParam String biaoShiHao) {
        try {
            dknClosePlanService.removeById(biaoShiHao);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }




    @ApiOperation(value = "提交排产数据")
    @PostMapping("/productionPlanAdd")
    public CommonResult productionPlanAdd(@RequestBody JSONObject jsonObject) {
        try {
            if(UtilValidate.isEmpty(jsonObject.get("planDateList"))){
                return CommonResult.error("排产数据不能为空!");
            }
            if(UtilValidate.isEmpty(jsonObject.get("selectOrderNo"))){
                return CommonResult.error("请先选择排产数据!");
            }
            String s = dknMainPlanService.productionPlanAdd(jsonObject);
            return CommonResult.success(s);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "排产记录")
    @PostMapping("/mainPlanList")
    public CommonResult mainPlanList(DknMainPlanQueryCriteria criteria, YmPageDto pageDto) {
        try {

            TableList<DknMainPlan> list = dknMainPlanService.list(criteria, pageDto);
            return CommonResult.success(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "根据日期查询提交记录")
    @PostMapping("/getDateRangeItems")
    public CommonResult getDateRangeItems(@RequestBody List<String> date_rang) {
        try {
            if(UtilValidate.isEmpty(date_rang)){
                return CommonResult.error("数据不能为空!");
            }
            List<DknPlanItem> dateRangeItems = dknPlanItemService.getDateRangeItems(date_rang);
            return CommonResult.success(dateRangeItems);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取排产计划详情数据")
    @PostMapping("/getMainPlan")
    public CommonResult getMainPlan(@RequestParam String mainId) {
        try {
            DknMainPlan mainPlan = dknMainPlanService.getById(mainId);
            return CommonResult.success(mainPlan, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除排产计划详情数据")
    @PostMapping("/removeMainPlan")
    public CommonResult removeMainPlan(@RequestParam String mainId) {
        try {
            dknMainPlanService.removeById(mainId);

            LambdaQueryWrapper<DknItemPlan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DknItemPlan::getMainId, mainId);
            dknItemPlanService.remove(queryWrapper);

            LambdaQueryWrapper<DknPlanItem> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(DknPlanItem::getMainId, mainId);
            dknPlanItemService.remove(queryWrapper2);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "同步 forecast 缓存")
    @PostMapping("/autoForecastCache2")
    public CommonResult autoForecastCache2() {
        try {
            dknForecastCacheService.autoForecastCache2();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "保存填写数据")
    @PostMapping("/saveForecastData")
    public CommonResult saveForecastData(@RequestBody JSONArray jsonArray) {
        try {
            dknForecastSaveService.saveForecast(jsonArray);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "清空填写数据")
    @PostMapping("/cleanForecastData")
    public CommonResult cleanForecastData() {
        try {
            dknForecastSaveService.cleanForecast();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

}
